package com.evolution.common.core.exception;

import com.evolution.common.core.context.SpringContext;
import com.evolution.common.core.enums.HttpStatus;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.io.Serial;
import java.util.Objects;

/**
 * Class: BaseException
 * <p>
 * desc: 基础异常
 * </p>
 * create date: 2024-03-07 13:08:14
 *
 * @author cao.yong
 */
public class BaseException extends RuntimeException {

    @Serial
    private static final long serialVersionUID = 1L;

    private static final int SERVER_ERROR_CODE = HttpStatus.SERVER_ERROR.getCode();

    private final MessageSource messageSource = SpringContext.getBean(MessageSource.class);

    /**
     * 所属模块
     */
    private final String module;

    /**
     * 异常码
     */
    private final int code;

    /**
     * 异常原因
     */
    private final String reason;

    /**
     * 异常原因的参数
     */
    private final Object[] args;

    public BaseException(String reason) {
        this(null, SERVER_ERROR_CODE, reason, new Object[0]);
    }

    public BaseException(String module, String reason) {
        this(module, SERVER_ERROR_CODE, reason, new Object[0]);
    }

    public BaseException(int code, String reason) {
        this(null, code, reason, new Object[0]);
    }


    public BaseException(int code, String reason, Object... args) {
        this(null, code, reason, args);
    }

    public BaseException(String reason, Object... args) {
        this(null, SERVER_ERROR_CODE, reason, args);
    }

    public BaseException(String module, int code, String reason, Object... args) {
        this.module = module;
        this.code = code;
        this.reason = reason;
        this.args = args;
    }

    public String getModule() {
        return module;
    }

    public int getCode() {
        return code;
    }

    public String getReason() {
        if (Objects.nonNull(reason)) {
            return messageSource.getMessage(reason, args, LocaleContextHolder.getLocale());
        }
        return "Unknown";
    }

    public Object[] getArgs() {
        return args;
    }
}
